<template>
    <div class="address-container">
        <div class="page-header">
            <h1 class="page-title">收货地址管理</h1>
            <p class="page-subtitle">管理您的收货地址信息</p>
            <el-button type="primary" @click="showAddDialog" class="add-btn">
                <el-icon><Plus /></el-icon>
                新增地址
            </el-button>
        </div>
        
        <div class="address-list">
            <div
                v-for="address in addresses"
                :key="address.id"
                class="address-card"
            >
                <div class="address-header">
                    <div class="recipient-info">
                        <span class="name">{{ address.receiver }}</span>
                        <span class="phone">{{ address.mobile }}</span>
                        <el-tag v-if="address.name" type="info" size="small">{{ address.name }}</el-tag>
                    </div>
                    <div class="actions">
                        <!-- <el-button
                            type="text"
                            @click="editAddress(address)"
                            class="action-btn"
                        >
                            <el-icon><Edit /></el-icon>
                            编辑
                        </el-button> -->
                        <el-button
                            type="text"
                            @click="deleteAddress(address)"
                            class="action-btn danger"
                        >
                            <el-icon><Delete /></el-icon>
                            删除
                        </el-button>
                    </div>
                </div>
                
                <div class="address-content">
                    <div class="address-text">
                        <el-icon><Location /></el-icon>
                        <span>{{ formatAddress(address) }}</span>
                    </div>
                    
                    <div class="address-actions">
                        <!-- 暂时移除设为默认功能 -->
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty v-if="addresses.length === 0" description="暂无收货地址">
            <el-button type="primary" @click="showAddDialog">
                添加第一个地址
            </el-button>
        </el-empty>
        
        <!-- 添加/编辑地址对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="editingAddress ? '编辑地址' : '新增地址'"
            width="600px"
            @close="resetForm"
        >
            <el-form
                ref="addressFormRef"
                :model="addressForm"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="地址名称" prop="name">
                    <el-input
                        v-model="addressForm.name"
                        placeholder="请输入地址名称（如：家、公司等）"
                        maxlength="40"
                    />
                </el-form-item>
                
                <el-form-item label="收货人" prop="receiver">
                    <el-input
                        v-model="addressForm.receiver"
                        placeholder="请输入收货人姓名"
                        maxlength="40"
                    />
                </el-form-item>
                
                <el-form-item label="手机号码" prop="mobile">
                    <el-input
                        v-model="addressForm.mobile"
                        placeholder="请输入手机号码"
                        maxlength="11"
                    />
                </el-form-item>
                
                <el-form-item label="所在地区" prop="region">
                    <el-cascader
                        v-model="addressForm.region"
                        :props="cascaderProps"
                        placeholder="请选择省/市/区"
                        style="width: 100%"
                        @change="handleRegionChange"
                    />
                </el-form-item>
                
                <el-form-item label="详细地址" prop="place">
                    <el-input
                        v-model="addressForm.place"
                        type="textarea"
                        rows="3"
                        placeholder="请输入详细地址（街道、门牌号等）"
                        maxlength="40"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button
                        type="primary"
                        @click="saveAddress"
                        :loading="saving"
                    >
                        {{ saving ? '保存中...' : '保存' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Location } from '@element-plus/icons-vue'
import { getAddress, addAddress, updateAddress, delAddress, getArea, getAreaDetail } from '@/api/user'

const addresses = ref([])
const dialogVisible = ref(false)
const editingAddress = ref(null)
const addressFormRef = ref()
const saving = ref(false)

// 懒加载地区数据
const lazyLoadRegion = async (node, resolve) => {
    const { level, value } = node
    
    try {
        let data = []
        
        if (level === 0) {
            // 加载省份数据
            const result = await getArea()
            data = result || []
        } else {
            // 加载市/区数据
            const result = await getAreaDetail(value)
            // 处理响应格式：{"id":110000,"area_set":[{"id":110100,"name":"直辖市"}],"name":"北京市"}
            data = result?.area_set || []
        }
        
        // 转换数据格式
        const nodes = data.map(item => ({
            id: item.id,
            name: item.name,
            value: item.id,
            label: item.name,
            leaf: level >= 2 // 区级是叶子节点
        }))
        
        resolve(nodes)
    } catch (error) {
        console.error('获取地区数据失败:', error)
        resolve([])
    }
}

// 级联选择器配置
const cascaderProps = {
    value: 'id',
    label: 'name',
    children: 'children',
    lazy: true,
    lazyLoad: lazyLoadRegion
}

const addressForm = reactive({
    name: '',
    receiver: '',
    mobile: '',
    region: [],
    place: ''
})

const rules = reactive({
    name: [
        { required: true, message: '请输入地址名称', trigger: 'blur' },
        { min: 2, max: 40, message: '地址名称长度为2-40个字符', trigger: 'blur' }
    ],
    receiver: [
        { required: true, message: '请输入收货人姓名', trigger: 'blur' },
        { min: 2, max: 40, message: '收货人姓名长度为2-40个字符', trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    region: [
        { required: true, message: '请选择所在地区', trigger: 'change' }
    ],
    place: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
        { min: 5, max: 40, message: '详细地址长度为5-40个字符', trigger: 'blur' }
    ]
})

// 获取地址列表
const fetchAddresses = async () => {
    try {
        const data = await getAddress()
        addresses.value = data.map(item => ({
            id: item.id,
            name: item.name,
            receiver: item.receiver,
            mobile: item.mobile,
            province: item.province,
            city: item.city,
            district: item.district,
            province_name: item.province_name,
            city_name: item.city_name,
            district_name: item.district_name,
            place: item.place
        }))
    } catch (error) {
        console.error('获取地址列表失败:', error)
        ElMessage.error('获取地址列表失败')
    }
}


// 格式化地址
const formatAddress = (address) => {
    return `${address.province_name || address.province || ''} ${address.city_name || address.city || ''} ${address.district_name || address.district || ''} ${address.place || ''}`
}

// 显示添加对话框
const showAddDialog = () => {
    editingAddress.value = null
    dialogVisible.value = true
}

// 编辑地址
const editAddress = (address) => {
    editingAddress.value = address
    
    // 构建地区选择数组
    const regionArray = []
    if (address.province) regionArray.push(address.province)
    if (address.city) regionArray.push(address.city)
    if (address.district) regionArray.push(address.district)
    
    Object.assign(addressForm, {
        name: address.name,
        receiver: address.receiver,
        mobile: address.mobile,
        region: regionArray,
        place: address.place
    })
    dialogVisible.value = true
}

// 删除地址
const deleteAddress = async (address) => {
    try {
        await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await delAddress(address.id)
        ElMessage.success('删除成功')
        fetchAddresses()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除地址失败:', error)
            ElMessage.error('删除地址失败')
        }
    }
}

// 设为默认地址功能已移除（后端模型中没有相关字段）

// 保存地址
const saveAddress = async () => {
    if (!addressFormRef.value) return
    
    try {
        await addressFormRef.value.validate()
        
        saving.value = true
        
        const formData = {
            name: addressForm.name,
            receiver: addressForm.receiver,
            mobile: addressForm.mobile,
            province: addressForm.region[0] || null,
            city: addressForm.region[1] || null,
            district: addressForm.region[2] || null,
            place: addressForm.place
        }
        
        if (editingAddress.value) {
            // 编辑地址
            await updateAddress(editingAddress.value.id, formData)
            ElMessage.success('地址更新成功')
        } else {
            // 新增地址
            await addAddress(formData)
            ElMessage.success('地址添加成功')
        }
        
        dialogVisible.value = false
        fetchAddresses()
        
    } catch (error) {
        console.error('保存地址失败:', error)
        ElMessage.error('保存地址失败')
    } finally {
        saving.value = false
    }
}

// 处理地区变化
const handleRegionChange = (values) => {
    console.log('地区变化:', values)
    // 这里可以添加其他地区变化的处理逻辑
}

// 重置表单
const resetForm = () => {
    Object.assign(addressForm, {
        name: '',
        receiver: '',
        mobile: '',
        region: [],
        place: ''
    })
    
    if (addressFormRef.value) {
        addressFormRef.value.clearValidate()
    }
}

onMounted(() => {
    fetchAddresses()
})
</script>

<style lang="less" scoped>
.address-container {
    padding: 20px;
    max-width: 1000px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ecf0f1;
    
    .page-title {
        font-size: 28px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }
    
    .page-subtitle {
        color: #7f8c8d;
        font-size: 14px;
        margin: 0;
    }
    
    .add-btn {
        background: linear-gradient(45deg, #667eea, #764ba2);
        border: none;
        border-radius: 8px;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.3);
        }
    }
}

.address-list {
    display: grid;
    gap: 20px;
    
    .address-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        border: 2px solid transparent;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
        }
        

        
        .address-header {
            padding: 20px 24px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #f5f5f5;
            
            .recipient-info {
                display: flex;
                align-items: center;
                gap: 12px;
                
                .name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #2c3e50;
                }
                
                .phone {
                    color: #7f8c8d;
                    font-size: 14px;
                }
            }
            
            .actions {
                display: flex;
                gap: 8px;
                
                .action-btn {
                    padding: 4px 8px;
                    font-size: 12px;
                    
                    &.danger {
                        color: #e74c3c;
                        
                        &:hover {
                            color: #c0392b;
                        }
                    }
                }
            }
        }
        
        .address-content {
            padding: 16px 24px 20px;
            
            .address-text {
                display: flex;
                align-items: flex-start;
                gap: 8px;
                margin-bottom: 16px;
                
                .el-icon {
                    color: #7f8c8d;
                    margin-top: 2px;
                }
                
                span {
                    color: #2c3e50;
                    line-height: 1.5;
                }
            }
            
            .address-actions {
                display: flex;
                justify-content: flex-end;
            }
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .address-container {
        padding: 15px;
    }
    
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
        
        .add-btn {
            width: 100%;
        }
    }
    
    .address-card {
        .address-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
            
            .actions {
                width: 100%;
                justify-content: flex-end;
            }
        }
    }
}
</style> 